import React from "react";
import { StyleSheet, Linking } from "react-native";
import { Text } from "@rneui/themed";
import { useTheme } from "@/contexts/ThemeContext";

const urlReg = /https?:\/\/[^\s]+/g;

export default function LinkText({
  content,
  size = 16,
}: {
  content: string;
  size?: number;
}) {
  const { colors } = useTheme();
  const parts: { text: string; isLink: boolean }[] = [];
  let lastIndex = 0;
  const matches = [...content.matchAll(urlReg)];
  matches.forEach((match) => {
    if (match.index! > lastIndex) {
      parts.push({
        text: content.slice(lastIndex, match.index),
        isLink: false,
      });
    }
    parts.push({ text: match[0], isLink: true });
    lastIndex = match.index! + match[0].length;
  });
  if (lastIndex < content.length) {
    parts.push({ text: content.slice(lastIndex), isLink: false });
  }

  return (
    <Text style={[styles.text, { fontSize: size, color: colors.text.primary }]}>
      {parts.map((part, index) =>
        part.isLink ? (
          <Text
            key={index}
            style={[styles.link, { color: colors.primary }]}
            onPress={() => Linking.openURL(part.text)}
          >
            {part.text}
          </Text>
        ) : (
          <Text key={index}>{part.text}</Text>
        )
      )}
    </Text>
  );
}

const styles = StyleSheet.create({
  text: {
    lineHeight: 22,
  },
  link: {
    textDecorationLine: "underline",
  },
});
